class ApplicationController < ActionController::Base

  protect_from_forgery
  
  before_filter :error_message_follows_field,
    :current_user_id,
    :authorize
  
  # 校验错误信息显示在field后面
  def error_message_follows_field
    error_message_follows_field_by_default
  end
  
  def error_message_follows_field_by_default
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|      
      if instance.error_message.kind_of?(Array)
        %(#{html_tag}<span class="validation_error">&nbsp;#{instance.error_message.join(',')}</span>).html_safe

      else
        %(#{html_tag}<span class= "validation_error">&nbsp;#{instance.error_message}</span>).html_safe
      end
    end
  end
  
  def error_message_follows_field_in_new_line
    ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|      
      if instance.error_message.kind_of?(Array)
        %(#{html_tag}<span class="validation_error"><br/>#{instance.error_message.join(',')}</span>).html_safe

      else
        %(#{html_tag}<span class= "validation_error"><br/>#{instance.error_message}</span>).html_safe
      end
    end
  end
  
  def current_user
    User.find(current_user_id) if current_user_id.present?
  end
  
  def current_user_id
    if session[:current_user_id].nil? and cookies.signed[:user_id].present?
      begin
        user = User.find(cookies.signed[:user_id])
        session[:current_user_id] = user.id if user.check_security_key_in_cookies(cookies.signed[:user_security_key])        
      rescue ActiveRecord::RecordNotFound
        logger.debug "user.find(#{cookies.signed[:user_id]}) failed"
      end
    else
#      logger.debug "验证当前会员是否可用"
      session[:current_user_id] = nil if not User.exists?(session[:current_user_id])
    end          
    Thread.current[:current_user_id] = session[:current_user_id]
    session[:current_user_id]
  end

  def authorize
    respond_to do |format|
      format.html do
#        if baidu_has_loggined?  # 百度已经登录，则new一个用户和对应的企业
#          logger.debug "百度已经登录=================="
#        else
          redirect_to new_session_url :http_referer => request.request_uri
#          logger.debug "百度未登录=================="
#          access_token
#        end        
      end
      format.js do        
        redirect_to new_session_url(:format => :js)
      end
    end if not User.has_loggined? or User.current.status.locked?
  end

  # 创建client
  def client
    OAuth2::Client.new(Property.baidu_api_key, Property.baidu_secret_key, :site => Property.site, :authorize_url=> Property.authorize_url)
  end

  # 获得access_token
  def access_token
    redirect_to client.auth_code.authorize_url(:redirect_uri => "#{Property.dns}/oauth/callback")
  end

  # 校验是否baidu登录
  def baidu_has_loggined?
    secret_key = Property.baidu_secret_key #应用的Secret Key就是签名密钥
    bd_user = params[:bd_user]  #当前登录用户的user id，如果用户未登录，则该值为0
    bd_sig = params[:bd_sig]  #对所有以"bd_"为参数名前缀的参数（目前只有bd_user参数）的MD5签名'
    expected_sig = Digest::MD5.hexdigest("bd_user=#{bd_user}#{secret_key}")
    if expected_sig == bd_sig
      return true
    else
      return false
    end
  end
end
